package project

import (
	"context"
	"fmt"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/project/parameter"
	"reflect"
	"strings"
)

type MemberService struct{ memberDao string }

func init() {
	memberService := MemberService{
		memberDao: "project.MemberDao",
	}
	factory.Put(reflect.TypeOf(memberService).String(), &memberService)
}
func (s *MemberService) GetMemberDao() *MemberDao {
	return factory.Get(s.memberDao).(*MemberDao)
}
func (s *MemberService) ListMember(ctx context.Context, req *parameter.ListMemberReq) (res *parameter.ListMemberRes) {
	members := s.GetMemberDao().ListMember(ctx, req)
	return &parameter.ListMemberRes{
		Detail: members,
	}
}
func (s *MemberService) ListPosition(ctx context.Context, req *parameter.ListPositionReq) (res *parameter.ListPositionRes) {
	positions := s.GetMemberDao().ListPosition(ctx, req)
	return &parameter.ListPositionRes{
		Detail: positions,
	}
}
func (s *MemberService) ListMemberSelected(ctx context.Context, req *parameter.ListMemberSelectedReq) (res *parameter.ListMemberSelectedRes) {
	users := s.GetMemberDao().GetMemberSelected(ctx, req)
	return &parameter.ListMemberSelectedRes{
		Detail: users,
	}
}
func (s *MemberService) GetMemberCombox(ctx context.Context, req *parameter.GetMemberComboxReq) (res *parameter.GetMemberComboxRes) {
	members := s.GetMemberDao().GetMemberCombox(ctx, req)
	for _, v := range members {
		if req.MemberId == v.Value {
			v.Selected = true
		}
	}
	return &parameter.GetMemberComboxRes{
		Detail: members,
	}
}

// CreateMember  创建成员
func (s *MemberService) CreateMember(ctx context.Context, req *parameter.CreateMemberReq) (res *parameter.CreateMemberRes) {
	if req.ProjectId == 0 {
		panic("项目ID为空")
	}
	if req.PositionId == 0 {
		panic("职位ID为空")
	}
	if strings.TrimSpace(req.UserIds) == "" {
		panic("成员ID为空")
	}
	//开启事务
	tx, err := s.GetMemberDao().DB().Begin(ctx)
	defer func() {
		if err != nil {
			tx.Rollback()
			fmt.Println("事务回滚")
			panic("添加成员失败")
		} else {
			tx.Commit()
			fmt.Println("事务提交")
		}
	}()
	s.GetMemberDao().CreateMember(tx, req)
	return res
}
func (s *MemberService) DeleteMember(ctx context.Context, req *parameter.DeleteMemberReq) (res *parameter.DeleteMemberRes) {
	if req.MemberId == 0 {
		panic("成员ID为空")
	}
	//开启事务
	tx, err := s.GetMemberDao().DB().Begin(ctx)
	defer func() {
		if err != nil {
			tx.Rollback()
			fmt.Println("事务回滚")
			panic("删除成员失败")
		} else {
			tx.Commit()
			fmt.Println("事务提交")
		}
	}()
	s.GetMemberDao().DeleteMember(tx, req)
	return res
}
